<template>
  <view class="min-h-screen w-full max-w-[750rpx] mx-auto bg-[#478b49]">
    <backView :back="goBack"/>

    <!-- 页面标题 -->
    <view class="bg-[#27c530] text-white p-[30rpx] rounded-b-[20rpx]">
      <text class="text-[32rpx] font-bold text-center block">{{PageItem.title}}</text>
    </view>

    <!-- 搜索栏 -->
    <!-- <view class="bg-white m-[24rpx] p-[24rpx] rounded-[20rpx] shadow-md">
      <view class="flex gap-[16rpx]">
        <nut-input v-model="searchForm.butlerName" placeholder="搜索健康管家姓名" class="flex-1" />
        <nut-button type="success" @click="searchRecords">搜索</nut-button>
      </view>
    </view> -->

    <!-- 我的健康管家介绍卡片 -->
    <view class="m-[24rpx] rounded-[24rpx] overflow-hidden shadow-2xl">
      <!-- 渐变背景 -->
      <view class="relative bg-gradient-to-br from-[#27c530] via-[#20a828] to-[#1a8f22] p-[32rpx]">
        <!-- 装饰性背景元素 -->
        <view class="absolute top-[-50rpx] right-[-50rpx] w-[200rpx] h-[200rpx] bg-white opacity-10 rounded-full"></view>
        <view class="absolute bottom-[-30rpx] left-[-30rpx] w-[150rpx] h-[150rpx] bg-white opacity-5 rounded-full"></view>
        
        <!-- 头部标题和切换按钮 -->
        <view class="flex items-center justify-between mb-[32rpx] relative z-10">
          <view>
            <text class="text-[36rpx] font-bold text-white block">我的健康管家</text>
            <text class="text-[24rpx] text-white opacity-80 mt-[4rpx]">Personal Health Butler</text>
          </view>
          <nut-button size="small" type="default" class="bg-white text-[#27c530] border-0 font-bold" @click="showSwitchModal = true">
            切换管家
          </nut-button>
        </view>
        
        <view v-if="loadingButler" class="relative z-10 text-center py-[60rpx]">
          <view class="w-[120rpx] h-[120rpx] bg-white bg-opacity-20 rounded-full flex items-center justify-center mx-auto mb-[24rpx]">
            <IconFont name="loading" size="60" color="white" />
          </view>
          <text class="text-[28rpx] text-white font-bold block mb-[12rpx]">正在加载健康管家信息...</text>
          <text class="text-[24rpx] text-white opacity-80">请稍候</text>
        </view>
        
        <view v-else-if="currentButler" class="relative z-10">
          <!-- 主要信息区域 -->
          <view class="bg-white bg-opacity-95 backdrop-blur-sm rounded-[20rpx] p-[32rpx] mb-[24rpx]">
            <view class="flex items-start">
              <!-- 头像区域 -->
              <view class="relative mr-[32rpx] flex-shrink-0">
                <view class="w-[140rpx] h-[140rpx] rounded-full bg-gradient-to-br from-[#27c530] to-[#1a8f22] flex items-center justify-center shadow-lg">
                  <IconFont font-class-name="iconfont" class-prefix="icon" size="70" color="white" name="geren" />
                </view>
                <!-- 在线状态指示器 -->
                <view class="absolute bottom-[8rpx] right-[8rpx] w-[24rpx] h-[24rpx] bg-green-400 rounded-full border-2 border-white"></view>
              </view>
              
              <!-- 基本信息 -->
              <view class="flex-1">
                <view class="flex items-center mb-[12rpx]">
                  <text class="text-[36rpx] font-bold text-gray-800 mr-[16rpx]">{{ currentButler.name || '未填写姓名' }}</text>
                  <view class="px-[16rpx] py-[6rpx] bg-gradient-to-r from-[#27c530] to-[#20a828] rounded-[16rpx] shadow-sm">
                    <text class="text-[22rpx] text-white font-medium">{{ currentButler.sex_dictText || '未知' }}</text>
                  </view>
                </view>
                
                <!-- 联系信息 -->
                <view class="flex items-center mb-[8rpx]">
                  <view class="w-[32rpx] h-[32rpx] bg-[#27c530] rounded-full flex items-center justify-center mr-[12rpx]">
                    <text class="text-[18rpx]">📱</text>
                  </view>
                  <text class="text-[28rpx] text-gray-700">{{ currentButler.phone || '未填写手机号' }}</text>
                </view>
                
                <!-- 职业信息 -->
                <view class="flex items-center mb-[8rpx]">
                  <view class="w-[32rpx] h-[32rpx] bg-[#27c530] rounded-full flex items-center justify-center mr-[12rpx]">
                    <text class="text-[18rpx]">🏥</text>
                  </view>
                  <text class="text-[28rpx] text-gray-700">{{ getHospitalName(currentButler.profile) || '未填写医院' }}</text>
                </view>
                
                <view class="flex items-center mb-[8rpx]">
                  <view class="w-[32rpx] h-[32rpx] bg-[#27c530] rounded-full flex items-center justify-center mr-[12rpx]">
                    <text class="text-[18rpx]">🏢</text>
                  </view>
                  <text class="text-[28rpx] text-gray-700">{{ getDepartmentName(currentButler.profile) || '未填写科室' }}</text>
                </view>
                
                <view class="flex items-center">
                  <view class="w-[32rpx] h-[32rpx] bg-[#27c530] rounded-full flex items-center justify-center mr-[12rpx]">
                    <text class="text-[18rpx]">👩‍⚕️</text>
                  </view>
                  <text class="text-[28rpx] text-gray-700">{{ getPositionName(currentButler.profile) || '未填写职位' }}</text>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 统计信息卡片 -->
          <view class="bg-white bg-opacity-95 backdrop-blur-sm rounded-[20rpx] p-[24rpx] mb-[24rpx]">
            <view class="flex items-center justify-between">
              <view class="text-center flex-1">
                <text class="text-[32rpx] font-bold text-[#27c530] block">{{ currentButler.rate || 0 }}</text>
                <text class="text-[22rpx] text-gray-600">服务评分</text>
              </view>
              <view class="w-[2rpx] h-[60rpx] bg-gray-200"></view>
              <view class="text-center flex-1">
                <text class="text-[32rpx] font-bold text-[#27c530] block">{{ currentButler.serverNumber || 0 }}</text>
                <text class="text-[22rpx] text-gray-600">服务次数</text>
              </view>
              <view class="w-[2rpx] h-[60rpx] bg-gray-200"></view>
              <view class="text-center flex-1">
                <text class="text-[32rpx] font-bold text-[#27c530] block">{{ currentButler.life || 0 }}</text>
                <text class="text-[22rpx] text-gray-600">健康指数</text>
              </view>
            </view>
          </view>
          
          <!-- 二维码区域 -->
          <view class="bg-white bg-opacity-95 backdrop-blur-sm rounded-[20rpx] p-[24rpx]">
            <view class="flex items-center justify-between">
              <view>
                <text class="text-[28rpx] font-bold text-gray-800 block mb-[8rpx]">个人二维码</text>
                <text class="text-[22rpx] text-gray-500">扫码添加健康管家</text>
              </view>
              <view class="w-[120rpx] h-[120rpx] bg-gray-100 rounded-[12rpx] flex items-center justify-center border-2 border-dashed border-gray-300" @click="showQRCode">
                <view v-if="currentButler.qrCode" class="w-full h-full">
                  <image :src="currentButler.qrCode" class="w-full h-full rounded-[8rpx]" mode="aspectFit" />
                </view>
                <view v-else class="text-center">
                  <IconFont name="scan" size="40" color="#27c530" />
                  <!-- <text class="text-[20rpx] text-gray-500 block mt-[8rpx]">生成二维码</text> -->
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <view v-else class="text-center py-[60rpx] relative z-10">
          <view class="w-[120rpx] h-[120rpx] bg-white bg-opacity-20 rounded-full flex items-center justify-center mx-auto mb-[24rpx]">
            <IconFont name="user" size="60" color="white" />
          </view>
          <text class="text-[32rpx] text-white font-bold block mb-[12rpx]">暂未选择健康管家</text>
          <text class="text-[24rpx] text-white opacity-80 block mb-[32rpx]">请选择您的专属健康管家</text>
          <nut-button type="default" class="bg-white text-[#27c530] border-0 font-bold px-[48rpx]" @click="showSwitchModal = true">
            选择管家
          </nut-button>
        </view>
      </view>
    </view>

    <!-- 切换管家弹窗 -->
    <nut-popup v-model:visible="showSwitchModal" position="bottom" :style="{ height: '70%' }">
      <view class="h-full flex flex-col">
        <view class="p-[24rpx] border-b border-gray-200 flex items-center justify-between">
          <text class="text-[32rpx] font-bold">选择健康管家</text>
          <view class="w-[40rpx] h-[40rpx] flex items-center justify-center" @click="showSwitchModal = false">
            <IconFont name="close" size="20" color="#666" />
          </view>
        </view>
        
        <view class="flex-1 overflow-y-auto">
          <view v-if="records.length === 0" class="text-center py-[100rpx]">
            <text class="text-[56rpx] mb-[16rpx] block">👤</text>
            <text class="text-[28rpx] text-gray-500">暂无健康管家</text>
          </view>
          
          <view v-else class="p-[24rpx]">
            <view v-for="record in records" :key="record.id" 
                  class="bg-white mb-[16rpx] rounded-[16rpx] shadow-sm border border-gray-100 overflow-hidden cursor-pointer transition-all duration-300 active:scale-98"
                  :class="{ 'border-[#27c530] bg-green-50': currentButler?.id === record.id }"
                  @click="selectButler(record)">
              <view class="p-[20rpx]">
                <view class="flex items-center">
                  <view class="w-[80rpx] h-[80rpx] rounded-full bg-[#adddaf] flex items-center justify-center mr-[20rpx]">
                    <IconFont font-class-name="iconfont" class-prefix="icon" size="40" color="#008822" name="geren" />
                  </view>
                  <view class="flex-1">
                    <view class="flex items-center mb-[4rpx]">
                      <text class="text-[28rpx] font-bold text-gray-800 mr-[12rpx]">{{ record.name || '未填写姓名' }}</text>
                      <view class="px-[8rpx] py-[2rpx] bg-[#27c530] rounded-[8rpx]">
                        <text class="text-[18rpx] text-white">{{ record.sex_dictText || '未知' }}</text>
                      </view>
                    </view>
                    <text class="text-[24rpx] text-gray-500 block mb-[4rpx]">{{ record.phone || '未填写手机号' }}</text>
                    <text class="text-[22rpx] text-gray-400">{{ getHospitalName(record.profile) || '未填写医院' }}</text>
                  </view>
                  <view v-if="currentButler?.id === record.id" class="w-[40rpx] h-[40rpx] rounded-full bg-[#27c530] flex items-center justify-center">
                    <IconFont name="Check" color="white" size="16" />
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </nut-popup>

    <!-- 二维码弹窗 -->
    <nut-popup v-model:visible="showQRModal" position="center" :style="{ width: '80%', maxWidth: '600rpx' }">
      <view class="bg-white rounded-[24rpx] p-[40rpx] text-center">
        <view class="mb-[32rpx]">
          <text class="text-[32rpx] font-bold text-gray-800 block mb-[8rpx]">健康管家二维码</text>
          <text class="text-[24rpx] text-gray-500">{{ currentButler?.name || '未填写姓名' }}</text>
        </view>
        
        <view class="w-[300rpx] h-[300rpx] bg-gray-100 rounded-[16rpx] mx-auto mb-[32rpx] flex items-center justify-center border-2 border-dashed border-gray-300">
          <view v-if="currentButler?.qrCode" class="w-full h-full">
            <image :src="currentButler.qrCode" class="w-full h-full rounded-[12rpx]" mode="aspectFit" />
          </view>
          <view v-else class="text-center">
            <IconFont name="scan" size="60" color="#27c530" />
            <text class="text-[24rpx] text-gray-500 block mt-[16rpx]">生成中...</text>
          </view>
        </view>
        
        <view class="mb-[32rpx]">
          <text class="text-[24rpx] text-gray-600 block mb-[8rpx]">扫码添加健康管家</text>
          <text class="text-[20rpx] text-gray-400">长按保存二维码到相册</text>
        </view>
        
        <view class="flex gap-[16rpx]">
          <nut-button size="small" type="default" class="flex-1" @click="showQRModal = false">
            <view class="flex items-center justify-center">
              <IconFont name="close" size="16" color="#666" class="mr-[8rpx]" />
              <text>关闭</text>
            </view>
          </nut-button>
          <nut-button size="small" type="primary" class="flex-1 bg-[#27c530]" @click="saveQRCode">保存到相册</nut-button>
        </view>
      </view>
    </nut-popup>

    </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import Taro from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import { PageItem } from './fields'
import { localStg } from '@/utils'
import backView from '@/components/backView.vue'
import { getHealthNurses } from '@/service/api/nurse_nurses'
import { useDemographicInfoStore } from '@/store'
import { request } from '@/service/request'

const records = ref<any[]>([])
const showSwitchModal = ref(false)
const showQRModal = ref(false)

// 获取 demographicStore 实例
const demographicStore = useDemographicInfoStore()

// 使用 demographicStore 中的健康管家信息
const currentButler = computed(() => demographicStore.currentHealthButler)
const loadingButler = computed(() => demographicStore.loadingButler)

Taro.useDidShow(loadRecords)

function goBack() {
  Taro.navigateBack()
}

async function loadRecords() {
  try {
    // const obj = localStg.get("demographicInfo");
    // const {success} = await request.get<any>(`${PageItem.commUrl}/list`, {
    //   recordid: obj.recordid
    // }, {
    //   useErrMsg: true
    // })
    
    // if (success.records) {
    //   records.value = success.records || []
    // }
    getHealthNurses().then(async res => {
      console.log(res, "res---------=======================");
      records.value = res.success.records || []
      
      // 加载当前选中的管家
      await loadCurrentButler()
    })
  } catch (error) {
    console.error('加载数据失败:', error)
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  }
}

// 加载当前选中的管家
async function loadCurrentButler() {
  try {
    // 优先从 demographicStore.currentInfo 中获取 healthId
    let butlerId = (demographicStore.currentInfo as any)?.healthId
    
    // 如果没有，则从本地存储获取
    if (!butlerId) {
      butlerId = localStg.get('currentButlerId')
    }
    
    if (butlerId) {
      // 使用 demographicStore 的方法获取健康管家信息
      await demographicStore.getHealthButlerById(butlerId)
    }
  } catch (error) {
    console.error('加载健康管家信息失败:', error)
    // 如果API调用失败，尝试从本地列表中找到
    const butlerId = localStg.get('currentButlerId')
    if (butlerId && records.value.length > 0) {
      const butler = records.value.find(record => record.id === butlerId)
      if (butler) {
        demographicStore.setHealthButler(butler)
      }
    }
  }
}

// 选择管家
async function selectButler(butler: any) {
  try {
    // 更新本地存储
    localStg.set('currentButlerId', butler.id)
    
    // 使用 demographicStore 的方法更新健康管家ID并自动获取详细信息
    const success = await demographicStore.updateHealthButlerId(butler.id)
    
    if (success) {
      // 调用 API 保存更新后的数据
      if (demographicStore.currentInfo) {
        await saveHealthRecordInfo(demographicStore.currentInfo)
      }
      
      showSwitchModal.value = false
      Taro.showToast({ title: '切换成功', icon: 'success' })
    } else {
      Taro.showToast({ title: '切换失败', icon: 'error' })
    }
  } catch (error) {
    console.error('切换管家失败:', error)
    Taro.showToast({ title: '切换失败', icon: 'error' })
  }
}

// 解析profile字段获取医院名称
function getHospitalName(profile: string) {
  if (!profile) return ''
  const lines = profile.split('\n')
  const hospitalLine = lines.find(line => line.includes('医院'))
  if (hospitalLine) {
    return hospitalLine.split('：')[1] || hospitalLine.split(':')[1] || ''
  }
  return ''
}

// 解析profile字段获取科室名称
function getDepartmentName(profile: string) {
  if (!profile) return ''
  const lines = profile.split('\n')
  const deptLine = lines.find(line => line.includes('科室'))
  if (deptLine) {
    return deptLine.split('：')[1] || deptLine.split(':')[1] || ''
  }
  return ''
}

// 解析profile字段获取职位名称
function getPositionName(profile: string) {
  if (!profile) return ''
  const lines = profile.split('\n')
  const positionLine = lines.find(line => line.includes('职位'))
  if (positionLine) {
    return positionLine.split('：')[1] || positionLine.split(':')[1] || ''
  }
  return ''
}

// 显示二维码
function showQRCode() {
  if (!currentButler.value) {
    Taro.showToast({ title: '请先选择健康管家', icon: 'none' })
    return
  }
  
  // 生成二维码内容
  const qrContent = generateQRContent(currentButler.value)
  
  // 这里可以调用二维码生成API或者使用本地生成
  // 暂时使用模拟数据
  if (!currentButler.value.qrCode) {
    currentButler.value.qrCode = generateQRCodeImage(qrContent)
  }
  
  showQRModal.value = true
}

// 生成二维码内容
function generateQRContent(butler: any) {
  const content = {
    type: 'health_butler',
    id: butler.id,
    name: butler.name,
    phone: butler.phone,
    hospital: getHospitalName(butler.profile),
    department: getDepartmentName(butler.profile),
    timestamp: Date.now()
  }
  return JSON.stringify(content)
}

// 生成二维码图片（模拟）
function generateQRCodeImage(content: string) {
  // 这里应该调用真实的二维码生成API
  // 暂时返回一个占位图片URL
  return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(content)}`
}

// 保存二维码到相册
async function saveQRCode() {
  if (!currentButler.value?.qrCode) {
    Taro.showToast({ title: '二维码未生成', icon: 'none' })
    return
  }
  
  try {
    // 下载图片到本地
    const downloadResult = await Taro.downloadFile({
      url: currentButler.value.qrCode
    })
    
    if (downloadResult.statusCode === 200) {
      // 保存到相册
      await Taro.saveImageToPhotosAlbum({
        filePath: downloadResult.tempFilePath
      })
      
      Taro.showToast({ title: '保存成功', icon: 'success' })
    } else {
      throw new Error('下载失败')
    }
  } catch (error) {
    console.error('保存二维码失败:', error)
    Taro.showToast({ title: '保存失败', icon: 'error' })
  }
}

// 保存健康档案信息
async function saveHealthRecordInfo(data: any) {
  try {
    const result = await request.put<any>('/health_records/HealthRecord/healthRecordInfo/edit', data, {
      useErrMsg: true
    })
    
    if (result) {
      console.log('健康档案信息保存成功:', result)
      // 更新本地存储
      localStg.set('demographicInfo', data)
      return true
    }
    return false
  } catch (error) {
    console.error('保存健康档案信息失败:', error)
    throw error
  }
}


</script>
